package com.cskaoyan.service.admin.storage;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.bean.vo.admin.promotion.AdminAdStorageVO;
import com.cskaoyan.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/*
 * @Auther:王贲
 * @Date:2022/9/6
 * @Description:
 * @VERSON:1.8
 */
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;


    @Override
    @Transactional
    public MarketStorage uploadFile(MultipartFile myfile) throws IOException {
        //文件大小
        long size = myfile.getSize();
        //获取原始文件名
        String originalFilename = myfile.getOriginalFilename();
        //获取正文类型
        String contentType = myfile.getContentType();
        //获取文件后缀
        String[] split = originalFilename.split("\\.");
        String suffix = "";
        if (split != null && split.length > 1) {
            suffix = split[split.length - 1];
        }
        //随机生成文件名，防止重复
        String uuidFileName = UUID.randomUUID().toString().replace("-","") + "." + suffix;
        //将文件保存到本地
        File file = new File("c:/43th_project2_picture/", uuidFileName);
        //文件上传
        myfile.transferTo(file);
        //将文件数据写入数据库
        MarketStorage storageVO = new MarketStorage();
        storageVO.setKey(uuidFileName);
        storageVO.setName(originalFilename);
        storageVO.setType(contentType);
        storageVO.setSize((int)size);
        //TODO 自行修改配置文件中的图片保存路径
        storageVO.setUrl("http://localhost:8083/wx/storageobject/fetch/" + uuidFileName);
        storageVO.setAddTime(new Date());


        storageVO.setUpdateTime(new Date());
        storageVO.setDeleted(false);
        //插入数据库
        marketStorageMapper.insert(storageVO);
        return storageVO;
    }
}
